import time

import requests
from requests import Response

from ..utils import log_util
from ..utils.utils import Utils
from ..conftest import global_env


class BaseApi:

    def __init__(self):
        self.path = Utils.get_root_path()
        self.yaml_path = self.path / "config/test.yaml"
        self.path_env = global_env.get("env")  # 根据命令行指令获取到运行的环境，默认是test

        self.yaml_data = Utils.get_yaml_data(self.yaml_path)
        self.base_url = self.yaml_data["base_url"]
        self.corpid = self.yaml_data[self.path_env]["corpid"]

    def send(self, req) -> Response:
        """

        @rtype: Response
        """
        log_util.logger.info(f"请求数据为：{req}")
        r = requests.request(**req)
        log_util.logger.info(f"请求对应的响应是: {r.json()}")
        return r

    def get_token(self):
        url = f"{self.base_url}/cgi-bin/gettoken"
        contact_corpsecret = self.yaml_data[self.path_env].get("contact").get("corpsecret")
        params = {
            'corpid': self.corpid,
            'corpsecret': contact_corpsecret
        }
        req = {
            "method": 'GET',
            "url": url,
            "params": params
        }
        r = self.send(req)
        token = r.json().get("access_token")
        return token
        pass

    def get_token_by_file(self):
        try:
            contact_token_data = self.yaml_data[self.path_env].get("contact").get("token")
            timestamp = contact_token_data.get("timestamp")
            contact_token = contact_token_data.get("access_token")
        except Exception as e:
            log_util.logger.info(f"获取数据出错，错误原因为：{e}")
            return e

        time_step = time.time() - timestamp
        # 判断 token 是否存在 以及时间戳是否过期
        if contact_token is None or time_step >= 7200:
            log_util.logger.info(f"由于token失效等问题，重新获取token")
            new_token = self.get_token()
            # 写入新数据
            self.yaml_data[self.path_env]["contact"]["token"] = {"timestamp": int(time.time()),
                                                                 "access_token": new_token}
            Utils.add_yaml_data(self.yaml_data, self.yaml_path)
            log_util.logger.info(f"token失效后，获取到的新token: {new_token}")
            # 返回新的token
            return new_token
        else:
            # 返回已有token
            return contact_token


a = BaseApi()
a.get_token_by_file()
